<?php
/**
 * @file name : filecontroller_model.php
 * @package   :
 * @author    : Vo Thanh Minh
 * @email     : <thanhminhld@yahoo.com - thanhminhld@gmail.com>
 * @copyright : 2011
 *
 */
if (!defined('BASEPATH')) {
    exit('No direct script access');
}

class Filecontroller_model extends Base_Model
{
    /**
     * @function __construct
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * @function createControlerModules
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   public
     * @param     array
     * @param     string
     * @return
     */
    public function createControlerModules($arrModule = array(), $projectName)
    {
        $filenameOnly = APPPATH . 'control_default/controller_edit_only.php';
        $filename     = APPPATH . 'control_default/controller.php';
        $fileUpload   = APPPATH . 'func_default/upload_file_func.php';
        $manFuncRecursive = APPPATH . 'func_default/manage_recursive.php';
        /**
         * Read file controller_edit_only
         */
        $fpOnly       = fopen($filenameOnly, 'r');
        $buffOnly     = '';
        if ($fpOnly) {
            while( ! feof($fpOnly)) {
                $buffOnly .= fgets($fpOnly);
            }
        }
        fclose($fpOnly);
        /**
         * Read file controller
         */
        $fp     = fopen($filename, 'r');
        $buff   = '';
        if ($fp) {
            while( ! feof($fp)) {
                $buff .= fgets($fp);
            }
        }
        fclose($fp);
        /**
         * Read file upload_file_func
         */
        $fp = fopen($fileUpload, 'r');
        $buffUpload = '';
        if ($fp) {
            while( ! feof($fp)) {
                $buffUpload .= fgets($fp);
            }
        }
        fclose($fp);
        /**
         * Read recursive func
         */
        $buffRecursive = '';
        $fp = fopen($manFuncRecursive, 'r');
        if ($fp) {
            while ( ! feof($fp)) {
                $buffRecursive .= fgets($fp);
            }
        }
        fclose($fp);

        /**
         * UCF_CTR_NAME : Upper character first of controller name
         * CTR_NAME     : Controller name
         * PROJ_NAME    : Project name
         * CPR          : Copyright
         * PRI_TBL_NAME : Primary table name
         * PRI_TBL_ID   : Primary table id
         */
        foreach ($arrModule as $key => $module) {
            if (! is_null($module->m_tbl_name) && strlen($module->m_tbl_name) > 0) {
                $controlName  = preg_replace('/_/', '', $module->m_name);
                $arrReplace   = array('\<CTR_NAME\>'     => $controlName,
                                      '\<UCF_CTR_NAME\>' => ucfirst($controlName),
                                      '\<PROJ_NAME\>'    => $projectName,
                                      '\<CPR\>'          => date('Y'),
                                      '\<PRI_TBL_NAME\>' => $module->tbl_pri_name,
                                      '\<PRI_TBL_ID\>'   => $module->tbl_pri_id,
                                      '\<TBL_PARENT_ID\>'=> $module->tbl_parent_id);
                $tmpBuff = '';
                if ($module->m_template_add == 'N' && $module->m_template_edit == 'Y') {
					// khong co them record ma chi co edit record
                    $tmpBuff = $buffOnly; // noi dung file controller chi co edit
                } else {
                    $tmpBuff = $buff; // noi dung file controller
                    $filed_info = array();
                    if (strlen($module->m_field_info) > 0) {
                        $arrTmp = explode(';', $module->m_field_info);
                        foreach ($arrTmp as $fieldInfo) {
                            $arrFieldTmp = explode(',', $fieldInfo);
                            array_push($filed_info, arrayFilter(':', $arrFieldTmp));
                        }
                    }
                    $tmpBuff = $this->createSaveFunc4Controller($module, $filed_info, $tmpBuff);
                    $tmpBuff = $this->createAddEditFunc4Controller($module, $filed_info, $tmpBuff);
                    $tmpBuff = $this->createDelFunc4Controller($module, $filed_info, $tmpBuff);
                }
                // Module da ca^p'
                if ($module->m_recursive == 'Y') {
                    $tmpBuff = preg_replace('/\<CHILD_CATE_RECURSIVE\>/', $buffRecursive, $tmpBuff);
                    $tmpBuff = preg_replace('/\<ASSIGN_CHILD_RECURSIVE\>/',
                                            '\'chidlCategoryList\'  => $chidlCategoryList,', $tmpBuff);
                } else {
                    $tmpBuff = preg_replace('/\<CHILD_CATE_RECURSIVE\>/', '', $tmpBuff);
                    $tmpBuff = preg_replace('/\<ASSIGN_CHILD_RECURSIVE\>/', '', $tmpBuff);
                }

                foreach ($arrReplace as $repKey => $val) {
                    $tmpBuff = preg_replace('/' . $repKey . '/', $val, $tmpBuff);
                }
                if ($module->m_upload_file == 'Y') {
                    $tmpBuff = preg_replace('/\<FILE_UPLOAD_FUNC\>/', $buffUpload, $tmpBuff);
                } else {
                    $tmpBuff = preg_replace('/\<FILE_UPLOAD_FUNC\>/', '', $tmpBuff);
                }
                $filenameControl = PROJECT_PATH . $projectName . '/administrator/application/controllers/'
                                 . $controlName . '.php';
                $fp = fopen($filenameControl, 'w');
                fwrite($fp, $tmpBuff);
                fclose($fp);

            } else {
                /**
                 * Tao Controller cho cac module cap con
                 */
                $arrWhere = array($module->m_id);
                $arrChildModule = $this->modules_model->loadListIn('parent_id', $arrWhere);
                foreach ($arrChildModule as $childKey => $childModule) {
                    if (! is_null($childModule->m_tbl_name) && strlen($childModule->m_tbl_name) > 0) {
                        $controlName  = preg_replace('/_/', '', $childModule->m_name);
                        $arrReplace   = array('\<CTR_NAME\>'     => $controlName,
                                              '\<UCF_CTR_NAME\>' => ucfirst($controlName),
                                              '\<PROJ_NAME\>'    => $projectName,
                                              '\<CPR\>'          => date('Y'),
                                              '\<PRI_TBL_NAME\>' => $childModule->tbl_pri_name,
                                              '\<PRI_TBL_ID\>'   => $childModule->tbl_pri_id,
                                              '\<TBL_PARENT_ID\>'=> $childModule->tbl_parent_id);
                        $tmpBuff = '';
                        if ($childModule->m_template_add == 'N' && $childModule->m_template_edit == 'Y') {
							// khong co them record ma chi co edit record
                            $tmpBuff = $buffOnly; // noi dung file controller chi co edit
                        } else {
                            $tmpBuff = $buff; // noi dung file controller
                            $filed_info = array();
                            if (strlen($childModule->m_field_info) > 0) {
                                $arrTmp = explode(';', $childModule->m_field_info);
                                foreach ($arrTmp as $fieldInfo) {
                                    $arrFieldTmp = explode(',', $fieldInfo);
                                    array_push($filed_info, arrayFilter(':', $arrFieldTmp));
                                }
                            }
                            $tmpBuff = $this->createSaveFunc4Controller($childModule, $filed_info, $tmpBuff);
                            $tmpBuff = $this->createAddEditFunc4Controller($childModule, $filed_info, $tmpBuff);
                            $tmpBuff = $this->createDelFunc4Controller($childModule, $filed_info, $tmpBuff);
                        }
                        // Module da ca^p'
                        if ($childModule->m_recursive == 'Y') {
                            $tmpBuff = preg_replace('/\<CHILD_CATE_RECURSIVE\>/', $buffRecursive, $tmpBuff);
                            $tmpBuff = preg_replace('/\<ASSIGN_CHILD_RECURSIVE\>/',
                                                    '\'chidlCategoryList\'  => $chidlCategoryList,', $tmpBuff);
                        } else {
                            $tmpBuff = preg_replace('/\<CHILD_CATE_RECURSIVE\>/', '', $tmpBuff);
                            $tmpBuff = preg_replace('/\<ASSIGN_CHILD_RECURSIVE\>/', '', $tmpBuff);
                        }
                        foreach ($arrReplace as $repKey => $val) {
                            $tmpBuff = preg_replace('/' . $repKey . '/', $val, $tmpBuff);
                        }
                        if ($childModule->m_upload_file == 'Y') {
                            $tmpBuff = preg_replace('/\<FILE_UPLOAD_FUNC\>/', $buffUpload, $tmpBuff);
                        } else {
                            $tmpBuff = preg_replace('/\<FILE_UPLOAD_FUNC\>/', '', $tmpBuff);
                        }
                        $filenameControl = PROJECT_PATH . $projectName . '/administrator/application/controllers/'
                                         . $controlName . '.php';
                        $fp = fopen($filenameControl, 'w');
                        fwrite($fp, $tmpBuff);
                        fclose($fp);
                    }
                }
            }
        }
    }
    /**
     * @function createSaveFunc4Controller
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    array $filed_info
     * @param    string $buffContrl
     * @return   string
     */
    private function createSaveFunc4Controller($module, $filed_info, $buffContrl)
    {
        /**
         * Create save function for module
         */
        $strSaveFunc = '';

        $strProcessFileUpload = '';
        if ( ! is_null($module->sub_id) && strlen($module->sub_id) > 0) {
            $arrSubModule = $this->modules_model->loadListIn('m_id', explode(',', $module->sub_id));
            foreach ($arrSubModule as $parentField) {
                $strSaveFunc .= '            '
                             . '$data[\'' . $parentField->tbl_pri_id . '\'] = $this->input->post(\''
                             . $parentField->tbl_pri_id. '\');' . "\n";
            }
        }
        foreach($filed_info as $key => $field) {

            if($field['field_type'] == 'Text' || $field['field_type'] == 'TextArea' ||
               $field['field_type'] == 'CheckBox') {
                $strSaveFunc .= '            ';
                $strSaveFunc .= '$data[\'' . $field['field_name']. '\'] = $this->input->post(\'' .
                                $field['field_name'] .'\');' . "\n";
            }
            if ($field['field_type'] == 'File' && $strProcessFileUpload == '') {
                $strProcessFileUpload = '            '
                                      . 'if (isset($_FILES[\'' . $field['field_name']. '\'][\'name\']) && ' . "\n"
                                      . '                '
                                      . 'strlen($_FILES[\'' . $field['field_name']. '\'][\'name\']) > 0) {' . "\n"
                                      . '                '
                                      . '$response = $this->do_upload(\'' . $field['field_name']. '\', true, '
                                      . 'array(\'width\' => \'\', \'height\' => \'\'));' . "\n"
                                      . '                '
                                      . 'if ($response[\'status\'] == \'Error\') {' . "\n"
                                      . '                '
                                      . '    defaultPage($controlName);' . "\n"
									  . '    return false;'
                                      . '                '
                                      . '}' . "\n"
                                      . '                '
                                      . '$data[\'' . $field['field_name']. '\'] = $response[\'file_name\'];' . "\n"
                                      . '                //Delete old file' . "\n"
                                      . '                '
                                      . 'if (is_numeric($' . $module->tbl_pri_id . ') && $' . $module->tbl_pri_id
                                      . ' > 0) {' . "\n"
                                      . '                    '
                                      . '$moduleObj = $this-><CTR_NAME>_model->loadRecord($' . $module->tbl_pri_id
                                      . ', $this->lang_default, TRUE);' . "\n"
                                      . '                    ' . '$oldFile = \'\';' . "\n"
                                      . '                    '
                                      . 'if(is_boject($moduleObj)) {' . "\n"
                                      . '                        '
                                      . '$oldFile = $moduleObj->' . $field['field_name'] . ';' . "\n"
                                      . '                        '
                                      . 'if (file_exists(UPLOAD_PATH . $controlName . \'/\' . $oldFile)) {' . "\n"
                                      . '                            '
                                      . 'unlink(UPLOAD_PATH . $controlName . \'/\' . $oldFile);' . "\n"
                                      . '                        '
                                      . '}' . "\n"
									  . '                    '
									  . '}' . "\n"
                                      . '                '
                                      . '}' . "\n"
                                      . '            }' . "\n";
            }
        }

        $strSaveFunc = $strSaveFunc . $strProcessFileUpload;
        $fileSaveFunc = APPPATH . 'func_default/save_module_func.php';
        $fp = fopen($fileSaveFunc, 'r');
        if ($fp) {
            while( ! feof($fp)) {
                $strSaveFunc .= fgets($fp);
            }
        }
        fclose($fp);
        // replace save function to controller file
        $buffContrl = preg_replace('/\<SAVE_FUNCTION\>/', $strSaveFunc, $buffContrl);

        return $buffContrl;
    }
    /**
     * @function createAddEditFunc4Controller
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    array $filed_info
     * @param    string $buffContrl
     * @return   string
     *
     */
    private function createAddEditFunc4Controller($module, $filed_info, $buffContrl)
    {
        $strAddEdit = '';
        $strParentId = '';
        $strAssignParentId = '';
        $strCheckBox = '';
        $strAssignCheckBox = '';
        $i = 0;
        $m_name = str_replace('_', '', $module->m_name);
        foreach($filed_info as $key => $field) {
            if ($i == 0) {
                $strAddEdit .= '$arrLang[$k][\'' . $m_name . 'Obj\'] = $recd;' . "\n";
            }
            if ($field['field_type'] == 'CheckBox') {
                $strAddEdit .= '                    $' . $field['field_name'] .' = $recd->'
                            . $field['field_name'] . ';' . "\n";
                if ($field['data_default'] != '--Default value--') {
                    if ($i == 0) {
                        $strCheckBox .= '$' . $field['field_name'] . ' = \'' . $field['data_default'] . '\';' . "\n";
                    } else {
                        $strCheckBox .= '        $' . $field['field_name'] . ' = \'' . $field['data_default']
                                     .  '\';' . "\n";
                    }
                } else {
                    if ($i == 0) {
                        $strCheckBox .= '$' . $field['field_name'] . ' = \'\';' . "\n";
                    } else {
                        $strCheckBox .= '        $' . $field['field_name'] . ' = \'\';' . "\n";
                    }
                }
                $strAssignCheckBox .= '                      \'' . $field['field_name'] . '\'    => $'
                                   .  $field['field_name'] . ',' . "\n";
            }
            if ($field['field_type'] == 'ParentId') {
                    $strAddEdit .= '                    $' . $field['field_name'] .' = $recd->'
                                . $field['field_name'] . ';' . "\n";
                    $strParentId = '$' . $field['field_name'] . ' = -1;' . "\n";
                    $strAssignParentId = '\'' . $field['field_name'] . '\'  => $' . $field['field_name'] . ',' . "\n";
            }
            $i++;
        }
        // replace <VAR_CHECK_4_EDIT> in controller file
        $buffContrl = preg_replace('/\<VAR_CHECK_4_EDIT\>/', $strParentId . $strCheckBox, $buffContrl);
        // replace <ARR_LANG_EDIT> in controller file
        $buffContrl = preg_replace('/\<ARR_LANG_EDIT\>/', $strAddEdit, $buffContrl);
        // replace <VAR_ASSIGN_4_EDIT> in controller file
        $buffContrl = preg_replace('/\<VAR_ASSIGN_4_EDIT\>/', $strAssignParentId . $strAssignCheckBox, $buffContrl);

        return $buffContrl;
    }
    /**
     * @function createDelFunc4Controller
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    object
     * @param    array
     * @param    string
     * @return
     */
    private function createDelFunc4Controller($module, $filed_info, $buffContrl)
    {
        $strDelImg = '';
        foreach($filed_info as $key => $field) {
            if ($field['field_type'] == 'File') {
                $strDelImg .= '$arrModule = $this-><CTR_NAME>_model->loadRecord($<PRI_TBL_ID>);' . "\n"
                           .  '        '
                           .  'foreach($arrModule as $mObj) {' . "\n"
                           .  '            '
                           .  '$oldFile = $mObj->' . $field['field_name'] . ';' . "\n"
                           .  '            '
                           .  'if (file_exists($imgPath . $oldFile)) {' . "\n"
                           .  '                '
                           .  'unlink($imgPath . $oldFile);' . "\n"
                           .  '            '
                           .  '}' . "\n"
                           .  '            '
                           .  'break;' . "\n"
                           .  '        '
                           .  '}';
                break;
            }
        }
        // replace del function to controller file
        $buffContrl = preg_replace('/\<DEL_IMG_TBL\>/', $strDelImg, $buffContrl);
        return $buffContrl;
    }
}